package org.wwx.register.server.impl;

import org.wwx.register.model.ServiceInstance;
import org.wwx.register.server.RegistryServer;
import storage.ServiceStorage;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @date 2025/6/6
 * @author王闻薪
 */
public class BuiltInHttpServer implements RegistryServer {
    private final ServiceStorage storage;
    private com.sun.net.httpserver.HttpServer server;
    private final int port;

    public BuiltInHttpServer(ServiceStorage storage, int port) {
        this.storage = storage;
        this.port = port;
    }

    @Override
    public void start() throws IOException {
        server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(port), 0);

        // 注册服务端点
        server.createContext("/register", exchange -> {
            if ("POST".equals(exchange.getRequestMethod())) {
                // 简化处理 - 实际应解析JSON
                Map<String, String> params = parseQuery(exchange.getRequestURI().getQuery());
                String serviceName = params.get("serviceName");
                String host = params.get("host");
                int port = Integer.parseInt(params.get("port"));

                ServiceInstance instance = new ServiceInstance(host, port);
                storage.registerService(serviceName, instance);

                String response = "{\"instanceId\":\"" + instance.getId() + "\"}";
                exchange.sendResponseHeaders(200, response.length());
                exchange.getResponseBody().write(response.getBytes());
            } else {
                exchange.sendResponseHeaders(405, -1); // Method Not Allowed
            }
            exchange.close();
        });

        // 发现服务端点
        server.createContext("/discover", exchange -> {
            if ("GET".equals(exchange.getRequestMethod())) {
                String serviceName = exchange.getRequestURI().getQuery().split("=")[1];
                List<ServiceInstance> instances = storage.getServiceInstances(serviceName);

                StringBuilder response = new StringBuilder("[");
                for (ServiceInstance instance : instances) {
                    response.append(String.format(
                            "{\"id\":\"%s\",\"host\":\"%s\",\"port\":%d},",
                            instance.getId(), instance.getHost(), instance.getPort()
                    ));
                }
                if (!instances.isEmpty()) {
                    response.deleteCharAt(response.length() - 1);
                }
                response.append("]");

                exchange.getResponseHeaders().add("Content-Type", "application/json");
                exchange.sendResponseHeaders(200, response.length());
                exchange.getResponseBody().write(response.toString().getBytes());
            } else {
                exchange.sendResponseHeaders(405, -1);
            }
            exchange.close();
        });

        // 心跳端点
        server.createContext("/heartbeat", exchange -> {
            if ("POST".equals(exchange.getRequestMethod())) {
                Map<String, String> params = parseQuery(exchange.getRequestURI().getQuery());
                String serviceName = params.get("serviceName");
                String instanceId = params.get("instanceId");

                storage.renewLease(serviceName, instanceId);
                exchange.sendResponseHeaders(200, -1);
            } else {
                exchange.sendResponseHeaders(405, -1);
            }
            exchange.close();
        });

        server.start();
        System.out.println("Registry HTTP server running on port " + port);
    }

    @Override
    public void stop() {
        if (server != null) {
            server.stop(0);
            System.out.println("Registry HTTP server stopped");
        }
    }

    private Map<String, String> parseQuery(String query) {
        Map<String, String> params = new HashMap<>();
        if (query != null) {
            for (String param : query.split("&")) {
                String[] pair = param.split("=");
                if (pair.length == 2) {
                    params.put(pair[0], pair[1]);
                }
            }
        }
        return params;
    }
}